//Columna Eliminar Registro
var deleteTd = "<td style = 'text-align: center'>";
var closeTd = "</td>";

var thAdditional = "<th>Proveedor</th>"+
                "<th>Cantidad</th>"+
                "<th>Descipción</th>"+               
                "<th>Monto Proveedor</th>"+
                "<th>Monto Cliente</th>"+
                "<th></th>";

var thFuel =  "<th># Orden</th> "+
                " <th>Litros Cabezal</th>"+
               " <th>Litros Chasis</th>"+
               "  <th>Estación</th>   "+              
               "  <th>Precio/Litro</th>"+
                " <th>Tipo Cambio</th>"+
                " <th>Tipo Pago</th>"+
                " <th># Referencia</th>"+
                "<th></th>";

var thAdvance = "<th>Proveedor</th>"+
                 "<th>Tipo Cambio</th>"+
                 "<th>Monto ($)</th>"+          
                 "<th>Tipo Pago</th>"+
                 "<th># Referencia</th>"+
                 "<th></th>";
var thOrders = " <th># Orden</th>"+
                "<th>Gasolinera</th>"+
                 "<th>Litros para el Cabezal</th>"+
                 "<th>Litros para el Chasis</th>"+               
                 "<th>Nombre del Chofer</th>"+
                 "<th>Placa del Camión</th>"+
                 "<th></th>";
/**####################### Carga de datos de opciones abanzadas #####################################*/

//Obtenemos la lista de los adicionales
function getProviders(){

    var containerValue = $("#containerId").val();
    var bkValue = $("#bk").val();

    $.ajax({
        data: {
            container : containerValue, bk : bkValue
        },
        url:  getProvidersAction,
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
        },
        success:  function (provider) {
           
                
                    var providerLabel = null; 
                    //Si los proveedores de chasis y cabezal son el mismos
                    if (provider['proveedor_cb'].id_proveedor == provider['proveedor_ch'].id_proveedor){
                        //Se oculta el input del proveedor de chasis y el label
                        $( "#chasisProviderAdditional" ).hide();
                        $( "#chasisProviderAdvance" ).hide();
                        $( "label[name^='providerCHLabel']" ).text("");
                        //Asignamos el valor del input al proveedor del chasis
                        $("#chasisProvider").val(provider['proveedor_cb'].id_proveedor);

                        //Se le asigna el label del nombre del proveedor
                        providerLabel = provider['proveedor_cb'].nombre;
                        //Asignamos el valor de los inputs referentes al cabezal
                        $( "#cabezalProviderFuel" ).val(provider['proveedor_cb'].id_proveedor);
                        $( "#cabezalProviderAdditional" ).val(provider['proveedor_cb'].id_proveedor);
                        $( "#cabezalProviderAdditional" ).attr("checked", true);
                        $( "#cabezalProviderAdvance" ).val(provider['proveedor_cb'].id_proveedor);
                        $( "#cabezalProviderAdvance" ).attr("checked", true);
                        $( "label[name^='providerCBLabel']" ).text(providerLabel);
                        $("#cabezalProvider").val(provider['proveedor_cb'].id_proveedor);
                        $("#provider").val(provider['proveedor_cb'].id_proveedor);
                        $("#providerAdvance").val(provider['proveedor_cb'].id_proveedor);                    
                        $("#providerDesc").val(providerLabel);
                        $("#providerAdvanceDesc").val(providerLabel);
                    }
                    else {
                        //asignamos los valores referentes al proveedor de cabezal
                        providerLabel = provider['proveedor_cb'].nombre+" - CB";

                        $( "#chasisProviderAdditional" ).show();
                        $( "#chasisProviderAdvance" ).show();

                        $( "#cabezalProviderFuel" ).val(provider['proveedor_cb'].id_proveedor);
                        $( "#cabezalProviderAdditional" ).val(provider['proveedor_cb'].id_proveedor);
                        $( "#cabezalProviderAdditional" ).attr("checked", true);
                        $( "#cabezalProviderAdvance" ).val(provider['proveedor_cb'].id_proveedor);
                        $( "#cabezalProviderAdvance" ).attr("checked", true);
                        $( "label[name^='providerCBLabel']" ).text(providerLabel);
                        $("#cabezalProvider").val(provider['proveedor_cb'].id_proveedor);
                        $("#provider").val(provider['proveedor_cb'].id_proveedor);
                        $("#providerAdvance").val(provider['proveedor_cb'].id_proveedor);                    
                        $("#providerDesc").val(providerLabel);
                        $("#providerAdvanceDesc").val(providerLabel);
                       
                        //Asignamos los valores referentes al proveedor de chasis
                        $( "#chasisProviderAdditional" ).val(provider['proveedor_ch'].id_proveedor);
                        $( "#chasisProviderFuel" ).val(provider['proveedor_ch'].id_proveedor);
                        $( "#chasisProviderAdvance" ).val(provider['proveedor_ch'].id_proveedor);
                        $( "label[name^='providerCHLabel']" ).text(provider['proveedor_ch'].nombre+" - CH");

                        $("#chasisProvider").val(provider['proveedor_ch'].id_proveedor);
                    }
            }
    });
}

//Obtenemos la lista de los adicionales
function getAdditionals(){
    var containerValue = $("#containerId").val();
    var bkValue = $("#bk").val();
    $("#additionalListTable").html(thAdditional);
    $.ajax({
        data: {
            container : containerValue,bk : bkValue
        },
        url:  getAdditionalsAction,
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
        },
        success:  function (response) {
           
            $.each(response, function(index, additional) {
                var providerValue = additional.nombre_proveedor
                var countValue = additional.cantidad;
                var descriptionValue = additional.descripcion;
                var supplierAmountCodeValue = additional.precio_proveedor;
                var clientAmountCodeValue = additional.precio_cliente;
                var idRow = additional.id_adicional;

                //Agregamos el html para mostrar el registro agregado
                var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteAdditional($(this).parent().parent().parent(),"+idRow+")'/></a>";
                var newdeleteTd = deleteTd+linkDelete+closeTd;
                var newRow = "<tr><td>"+providerValue+"</td><td>"+countValue+"</td><td>"+descriptionValue+"</td><td>"+supplierAmountCodeValue+"</td><td>"+clientAmountCodeValue+"</td>"+newdeleteTd+"</tr>";
                $("#additionalListTable").append(newRow);
                
            });

        }
    });
}
//Obtenemos la lista de los adicionales
function getFuels(){

    var containerValue = $("#containerId").val();
    var bkValue = $("#bk").val();
    $("#fuelListTable").html(thFuel);
    $.ajax({
        data: {
            container : containerValue,bk : bkValue
        },
        url:  getFuelsAction,
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
        },
        success:  function (response) {
           
            $.each(response, function(index, fuel) {
            var orderValue = fuel.id_orden;
            var litersPriceValue = fuel.precio_litro;
            var changeTypeValue = fuel.tipo_cambio;
            var paymentTypeValue = fuel.tipo_pago;
            var referenceValue = fuel.referencia;
            var cabezalLitters = 0;
            var chasisLitters = 0;
            if (null != fuel.litros_cabezal){
                cabezalLitters = fuel.litros_cabezal;
            }
            if (null != fuel.litros_chasis){
                chasisLitters = fuel.litros_chasis;
            }
            var stationDesc = fuel.nombre_estacion;
            var cabezalId = fuel.cabezalId;
            var chasisId = fuel.chasisId;
                //Agregamos el html para mostrar el registro agregado
            var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteFuel($(this).parent().parent().parent(),"+cabezalId+","+chasisId+","+orderValue+")'/></a>";
            var newdeleteTd = deleteTd+linkDelete+closeTd;
           
            var newRow = "<tr><td>"+orderValue+"</td><td>"+cabezalLitters+"</td><td>"+chasisLitters+"</td><td>"+stationDesc+"</td><td class = 'colonFormat'>"+litersPriceValue+"</td><td class='colonFormat'>"+changeTypeValue+"</td><td>"+paymentTypeValue+"</td><td>"+referenceValue+"</td>"+newdeleteTd+"</tr>";
            
            $("#fuelListTable").append(newRow);

            $(".colonFormat").formatCurrency({symbol: '₡'});
                
            });
        }
    });
}
//Obtenemos la lista de los adelantos
function getAdvances(){

    var containerValue = $("#containerId").val();
    var bkValue = $("#bk").val();
    $("#advancesListTable").html(thAdvance);
    $.ajax({
        data: {
            container : containerValue,bk : bkValue
        },
        url:  getAdvancesAction,
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
        },
        success:  function (response) {
           
            $.each(response, function(index, advance) {
                var providerValue = advance.nombre_proveedor;
                var changeTypeValue = advance.tipo_cambio;
                var amountValue = advance.monto;
                var paymentTypeValue = advance.tipo_pago;
                var referenceValue = advance.referencia;
                var idRow = advance.id_adelanto;

                //Agregamos el html para mostrar el registro agregado
                var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteAdvances($(this).parent().parent().parent(),"+idRow+")'/></a>";
                var newdeleteTd = deleteTd+linkDelete+closeTd;
                var newRow = "<tr><td>"+providerValue+"</td><td class='colonFormat'>"+changeTypeValue+"</td><td class = 'dolarFormat'>"+amountValue+"</td><td>"+paymentTypeValue+"</td><td>"+referenceValue+"</td>"+newdeleteTd+"</tr>";
                $("#advancesListTable").append(newRow);

                $(".dolarFormat").formatCurrency({symbol: '$'});
                $(".colonFormat").formatCurrency({symbol: '₡'});
            });
        }
    });
}
//Obtenemos la lista de los adelantos
function getOrders(){

    var containerValue = $("#containerId").val();
    var bkValue = $("#bk").val();
    $("#ordersListTable").html(thOrders);
    $.ajax({
        data: {
            container : containerValue,bk : bkValue
        },
        url:  getOrdersAction,
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
        },
        success:  function (response) {

           $("#order").empty();
            $.each(response, function(index, order) {

                var idRow = order.id_orden;
               
                var stationDesc = order.nombre_estacion;
                var cabezalLittersValue = order.litros_cabezal;
                var chasisLittersValue = order.litros_chasis;
                var driverValue = order.nombre_chofer;
                var plateNumberValue = order.placa;

                var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteOrder($(this).parent().parent().parent(),"+idRow+")'/></a>";
                var linkPrint = "&nbsp;<a href='#' ><img class='print' src = '/booking/public/images/imp.png' onclick = 'printOrder("+idRow+")'/></a>";
                var newdeleteTd = deleteTd+linkDelete+linkPrint+closeTd;
                var newRow = "<tr><td>"+idRow+"</td><td>"+stationDesc+"</td><td>"+cabezalLittersValue+"</td><td>"+chasisLittersValue+"</td><td>"+driverValue+"</td><td>"+plateNumberValue+"</td>"+newdeleteTd+"</tr>";
                $("#ordersListTable").append(newRow);
                if (order.estado == 'N'){
                    $("#order").append("<option value = '"+order.id_orden+"'>"+order.id_orden+"</option>");
                }                

            });
        }
    });
}
/**####################### Funciones de Agregar y Eliminar Registros ####################################*/

//Ejecuta la acción de agregar adicionales
function addAdditional(){
    
    var count = new LiveValidation('count');
    count.add( Validate.Presence );
    count.add( Validate.Numericality, { onlyInteger: true } );

    var description = new LiveValidation('description');
    description.add( Validate.Presence );
    description.add( Validate.Length, { maximum: 100 });


    if (LiveValidation.massValidate([count,description])){

        var providerValue = $("#provider").val();
        var providerDesc = $("#providerDesc").val();
        
        var countValue = $("#count").val();
    	var descriptionValue = $("#description").val();
        var supplierAmountCodeValue = $("#supplierAmountCode").val();
        var clientAmountCodeValue = $("#clientAmountCode").val();

    	var containerValue = $("#containerId").val();
    	var bkValue = $("#bk").val();
        var idRow = null;

    	$.ajax({
            data: {
            	container : containerValue,bk : bkValue, provider: providerValue,count : countValue, description: descriptionValue,supplierAmountCode : supplierAmountCodeValue,clientAmountCode : clientAmountCodeValue
            },
            url:  addAdditionalAction,
            type: 'post',
            beforeSend: function () {
            },
            success:  function (response) {
                idRow = response;

                //Agregamos el html para mostrar el registro agregado
                var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteAdditional($(this).parent().parent().parent(),"+idRow+")'/></a>";
                var newdeleteTd = deleteTd+linkDelete+closeTd;
                var newRow = "<tr><td>"+providerDesc+"</td><td>"+countValue+"</td><td>"+descriptionValue+"</td><td>"+supplierAmountCodeValue+"</td><td>"+clientAmountCodeValue+"</td>"+newdeleteTd+"</tr>";
                $("#additionalListTable").append(newRow);

                $("#count").val("");
                $("#description").val("");
            }
        });
    }
}
//Ejecuta la acción de agregar adicionales
function deleteAdditional(row, idValue){
    
    $.ajax({
        data: {
            additional : idValue
        },
        url:  deleteAdditionalAction,
        type: 'post',
        beforeSend: function () {
        },
        success:  function (response) {
            $(row).remove();
        }
    });
}
//Ejecuta la acción de agregar gasolina
function addFuel(){
    if ($("#order").val() == null){
        alert("Debe crear una orden para poder agregar combustible")
    }
    var litersPrice = new LiveValidation('litersPrice');
    litersPrice.add( Validate.Presence );
    litersPrice.add( Validate.Numericality);

    var changeType = new LiveValidation('changeType');
    changeType.add( Validate.Numericality);
    changeType.add( Validate.Presence );

    var reference = new LiveValidation('reference');
    reference.add( Validate.Presence );
    reference.add( Validate.Numericality, { onlyInteger: true } );
    reference.add( Validate.Length, { maximum: 20 });

    if (LiveValidation.massValidate([litersPrice,changeType,reference])){
        var orderValue = $("#order").val();
        var litersPriceValue = $("#litersPrice").val();
    	var changeTypeValue = $("#changeType").val();
        var paymentTypeValue = $("#paymentType").val();
    	var referenceValue = $("#reference").val();
        var cabezalProviderValue = $("#cabezalProvider").val();
        var chasisProviderValue = $("#chasisProvider").val();

    	var containerValue = $("#containerId").val();
    	var bkValue = $("#bk").val();
        var idRow = null;


    	$.ajax({
            data: {
            	container : containerValue, bk: bkValue, order: orderValue, litersPrice : litersPriceValue, changeType : changeTypeValue, paymentType : paymentTypeValue, reference : referenceValue, cabezalProvider: cabezalProviderValue, chasisProvider : chasisProviderValue
            },
            url:  addFuelAction,
            type: 'post',
            dataType: 'json',
            beforeSend: function () {
            },
            success:  function (response) {
                var stationDesc = response['nombre_estacion'];
                var cabezalLitters = 0;
                var chasisLitters = 0;
                if (null != response['litros_cabezal']){
                    cabezalLitters = response['litros_cabezal'];
                }
                if (null != response['litros_chasis']){
                    chasisLitters = response['litros_chasis'];
                }
                var cabezalId = response['cabezalId'];
                var chasisId = response['chasisId'];

                //Agregamos el html para mostrar el registro agregado

                var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteFuel($(this).parent().parent().parent(),"+cabezalId+","+chasisId+","+orderValue+")'/></a>";
                var newdeleteTd = deleteTd+linkDelete+closeTd;
               
                var newRow = "<tr><td>"+orderValue+"</td><td>"+cabezalLitters+"</td><td>"+chasisLitters+"</td><td>"+stationDesc+"</td><td class = 'colonFormat'>"+litersPriceValue+"</td><td class='colonFormat'>"+changeTypeValue+"</td><td>"+paymentTypeValue+"</td><td>"+referenceValue+"</td>"+newdeleteTd+"</tr>";
                
                $("#fuelListTable").append(newRow);
                $(".colonFormat").formatCurrency({symbol: '₡'});

                $("#order option[value='"+orderValue+"']").remove();
                
                $("#litersPrice").val("");
                $("#changeType").val("");
                $("#reference").val("");
            }
        });
    }
}
//Ejecuta la acción de agregar adicionales
function deleteFuel(row, idCabezal, idChasis, order){
    $.ajax({
        data: {
            cabezalId : idCabezal, chasisId : idChasis, orderId : order
        },
        url:  deleteFuelAction,
        type: 'post',
        beforeSend: function () {
        },
        success:  function (response) {
            $(row).remove();
            $("#order").append("<option value = '"+order+"'>"+order+"</option>");
        }
    });
}
//Ejecuta la acción de agregar adelantos
function addAdvances(){

    var advanceChangeType = new LiveValidation('advanceChangeType');
    advanceChangeType.add( Validate.Numericality);
    advanceChangeType.add( Validate.Presence );

    var amount = new LiveValidation('amount');
    amount.add( Validate.Presence );
    amount.add( Validate.Numericality);

    var advanceReference = new LiveValidation('advanceReference');
    advanceReference.add( Validate.Presence );
    advanceReference.add( Validate.Length, { maximum: 20 });


    if (LiveValidation.massValidate([advanceChangeType,amount, advanceReference])){

        var providerValue = $("#providerAdvance").val();
        var providerDesc = $("#providerAdvanceDesc").val();
        var currencyValue = $("#currency").val();
        var changeTypeValue = $("#advanceChangeType").val();
        var amountValue = $("#amount").val();
        var paymentTypeValue = $("#advancePaymentType").val();
        var referenceValue = $("#advanceReference").val();

        var containerValue = $("#containerId").val();
        var bkValue = $("#bk").val();
        var idRow = null;

        $.ajax({
            data: {
                container : containerValue,bk : bkValue,provider: providerValue,currency : currencyValue, changeType : changeTypeValue, amount: amountValue,paymentType : paymentTypeValue,reference: referenceValue
            },
            url: addAdvanceAction,
            type: 'post',
            beforeSend: function () {
            },
            success:  function (response) {
               
                idRow = response;
                //Mostramos el monto solo en Dolares
                if (currencyValue == "COLONES"){
                    amountValue = amountValue / changeTypeValue;
                }
                //Agregamos el html para mostrar el registro agregado
                var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteAdvances($(this).parent().parent().parent(),"+idRow+")'/></a>";
                var newdeleteTd = deleteTd+linkDelete+closeTd;
                var newRow = "<tr><td>"+providerDesc+"</td><td class = 'colonFormat'>"+changeTypeValue+"</td><td class = 'dolarFormat'>"+amountValue+"</td><td>"+paymentTypeValue+"</td><td>"+referenceValue+"</td>"+newdeleteTd+"</tr>";
                $("#advancesListTable").append(newRow);

                $(".dolarFormat").formatCurrency({symbol: '$'});
                $(".colonFormat").formatCurrency({symbol: '₡'});

                $("#advanceChangeType").val("");
                $("#amount").val("");
                $("#advanceReference").val("");
            }   
        });
    }
}
//Ejecuta la acción de agregar adicionales
function deleteAdvances(row, idValue){
    
    $.ajax({
        data: {
            advance : idValue
        },
        url:  deleteAdvanceAction,
        type: 'post',
        beforeSend: function () {
        },
        success:  function (response) {
            $(row).remove();
        }
    });
}

//Ejecuta la acción de agregar adicionales
function printOrder(order){
    
    $.ajax({
        data: {
            order : order
        },
        url:  printOrderAction,
        type: 'post',
        beforeSend: function () {
        },
        success:  function (response) {
            window.open("/booking/public/Orden compra combustible.pdf", '_blank');
        }
    });
}

//Ejecuta la acción de agregar ordenes
function addOrder(){
    var cabezalLitters = new LiveValidation('cabezalLitters');
    cabezalLitters.add( Validate.Numericality);
    cabezalLitters.add( Validate.Presence );

    var chasisLitters = new LiveValidation('chasisLitters');
    chasisLitters.add( Validate.Presence );
    chasisLitters.add( Validate.Numericality);

    var driver = new LiveValidation('driver');
    driver.add( Validate.Presence );
    driver.add( Validate.Length, { maximum: 20 });

    var plateNumber = new LiveValidation('plateNumber');
    plateNumber.add( Validate.Presence );
    plateNumber.add( Validate.Length, { maximum: 10 });


    if (LiveValidation.massValidate([cabezalLitters,chasisLitters, driver, plateNumber])){

        var stationValue = $("#station").val();
        var stationDesc = $("#station option:selected").text();
        var cabezalLittersValue = $("#cabezalLitters").val();
        var chasisLittersValue = $("#chasisLitters").val();
        var driverValue = $("#driver").val();
        var plateNumberValue = $("#plateNumber").val();

        var containerValue = $("#containerId").val();
        var bkValue = $("#bk").val();
        var idRow = null;

        $.ajax({
            data: {
                container : containerValue,bk : bkValue,station : stationValue, cabezalLitters : cabezalLittersValue, chasisLitters : chasisLittersValue, driver : driverValue, plateNumber : plateNumberValue
            },
            url: addOrderAction,
            type: 'post',
            beforeSend: function () {
            },
            success:  function (response) {
               
                idRow = response;
               
                //Agregamos el html para mostrar el registro agregado
                var linkDelete = "<a href='#' ><img class='delete' src = '/booking/public/images/delete.png' onclick = 'deleteOrder($(this).parent().parent().parent(),"+idRow+")'/></a>";
                var linkPrint = "&nbsp;<a href='#' ><img class='print' src = '/booking/public/images/imp.png' onclick = 'printOrder("+idRow+")'/></a>";
                var newdeleteTd = deleteTd+linkDelete+linkPrint+closeTd;
                var newRow = "<tr><td>"+idRow+"</td><td>"+stationDesc+"</td><td>"+cabezalLittersValue+"</td><td>"+chasisLittersValue+"</td><td>"+driverValue+"</td><td>"+plateNumberValue+"</td>"+newdeleteTd+"</tr>";
                $("#ordersListTable").append(newRow);

                $("#order").append("<option value = '"+idRow+"'>"+idRow+"</option>");

                $("#cabezalLitters").val("");
                $("#chasisLitters").val("");
                $("#driver").val("");
                $("#plateNumber").val("");
            }   
        });
    }
}
//Ejecuta la acción de agregar adicionales
function deleteOrder(row, idValue){
    
    $.ajax({
        data: {
            order : idValue
        },
        url:  deleteOrderAction,
        type: 'post',
        beforeSend: function () {
        },
        success:  function (response) {
            if (response == 'true'){
                $(row).remove();

                $("#order option[value='"+idValue+"']").remove();
            }
            else{
                alert("No se puede eliminar una orden asignada");
            }
        }
    });
}